package com.smh.demo1.a17;

import com.smh.demo1.a17.annotation.Yml;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.yaml.snakeyaml.Yaml;

import javax.servlet.http.HttpServletResponse;

/**
 * @author shiminghui
 * @date 2025/4/24 20:32
 * @description: TODO
 */
public class YmlReturnValueHandler implements HandlerMethodReturnValueHandler {
    public static void main(String[] args) {

        String dump = new Yaml().dump(new User(1L, "smh", 18));
        System.out.println(dump);

    }

    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return returnType.hasMethodAnnotation(Yml.class);
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
        // 将返回值转成yml格式的字符串
        String dump = new Yaml().dump(returnValue);
        // 设置响应
        HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
        response.setContentType("text/plain;charset:utf-8");
        response.getWriter().print(dump);

        // 设置请求处理完毕,无需进行视图解析等操作
        mavContainer.setRequestHandled(true);
    }

    static class User {
        private Long id;
        private String name;
        private Integer age;

        public User() {
        }

        public User(Long id, String name, Integer age) {
            this.id = id;
            this.name = name;
            this.age = age;
        }

        public Long getId() {
            return id;
        }

        public void setId(Long id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }
    }
}
